package com.zbowen.juc.queen;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.TimeUnit;

public class FairSpinLock {
    private AtomicReference<Thread> owner = new AtomicReference<>();
    private ConcurrentLinkedQueue<Thread> waiters = new ConcurrentLinkedQueue<>();

    public void lock(long timeout, TimeUnit unit) throws InterruptedException {
        Thread current = Thread.currentThread();
        waiters.add(current);
        long deadline = System.nanoTime() + unit.toNanos(timeout); // 计算超时截止时间
        while (true) {
            Thread first = waiters.peek();
            if (first == current) {
                if (!owner.compareAndSet(null, current)) {
                    continue;
                }
                waiters.poll();
                return;
            }
            if (System.nanoTime() > deadline) { // 判断是否超时
                waiters.remove(current); // 从等待队列中移除当前线程
                throw new InterruptedException("Timeout");
            }
            LockSupport.parkNanos(this, deadline - System.nanoTime()); // 等待一段时间再进行下一次尝试
        }
    }

    public void unlock() {
        Thread current = Thread.currentThread();
        if (!owner.compareAndSet(current, null)) {
            throw new IllegalMonitorStateException("Current thread is not the owner of the lock");
        }
        Thread next = waiters.peek();
        if (next != null) {
            LockSupport.unpark(next);
        }
    }
}